package com.awanp3.nimbus.wms.fg.aspect;

import com.awanp3.nimbus.common.core.exception.ServiceException;
import com.awanp3.nimbus.common.core.utils.StringUtils;
import com.awanp3.nimbus.common.tenant.helper.TenantHelper;
import com.awanp3.nimbus.system.api.RemoteTenantService;
import com.awanp3.nimbus.system.api.domain.vo.RemoteTenantVo;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.annotation.*;
import org.springframework.boot.autoconfigure.AutoConfiguration;

/**
 * 操作日志记录处理
 *
 * @author 20014170
 */
@Slf4j
@Aspect
@RequiredArgsConstructor
@AutoConfiguration
public class DatasourceAspect {

    @DubboReference
    private final RemoteTenantService remoteTenantService;

    /**
     * 切入点
     */
    @Pointcut("execution(* com.awanp3.nimbus.common.mybatis.core.mapper.BaseMapperPlus.*(..)) || execution(* com.awanp3.nimbus.wms.fg.mapper.*.*(..))")
    private void dbAspect() {
    }

    /**
     * 处理请求前执行
     */
    @Before(value = "dbAspect()")
    public void doBefore() {

        String tenantId = TenantHelper.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            throw new ServiceException("该模块相关功能需要指定数据源。");
        }
        RemoteTenantVo tenantVo = remoteTenantService.queryByTenantId(tenantId);
        if (StringUtils.isEmpty(tenantVo.getDatasource())) {
            throw new ServiceException("租户 " + tenantVo.getCompanyName() + " 没有配置数据源。");
        }
        DynamicDataSourceContextHolder.push(tenantVo.getDatasource());
    }


    /**
     * 处理请求后执行
     */
//    @After(value = "dbAspect()")
    public void doAfter() {
        DynamicDataSourceContextHolder.clear();
    }
}
